package www.ym.com.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import www.ym.com.common.CustomException;
import www.ym.com.common.R;
import www.ym.com.common.RL;
import www.ym.com.entity.MenuRole;
import www.ym.com.entity.Role;
import www.ym.com.entity.Staff;
import www.ym.com.entity.menu.Menu;
import www.ym.com.service.MenuRoleService;
import www.ym.com.service.MenuService;
import www.ym.com.service.RoleService;
import www.ym.com.service.StaffService;
import www.ym.com.utils.Md5Utils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

import static www.ym.com.utils.JWTUtils.createJWT;

@Slf4j
@RestController
@RequestMapping("/staff")
public class StaffController {

    @Autowired
    private StaffService staffService;

    @Autowired
    private MenuRoleService menuRoleService;

    @Autowired
    private MenuService menuService;

    /**
     * 新增员工信息
     *
     * @param staff
     * @return
     */
    @PostMapping("/addStaff")
    public R<String> add(@RequestBody Staff staff) {

        LambdaQueryWrapper<Staff> lambda = new LambdaQueryWrapper<>();
        lambda.eq(Staff::getPhone, staff.getPhone());
        int count = staffService.count(lambda);
        if (count > 0) {
            throw new CustomException("手机号码已被注册使用");
        }
        staff.setStatus(0);
        staffService.save(staff);
        return R.success(null, "新增员工成功");
    }

    /**
     * 分页信息
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("/list")
    public RL<Staff> staffPage(@RequestBody JSONObject jsonObject) {
        Page<Staff> staffPage = staffService.pageStaff(jsonObject);
        List<Staff> records = staffPage.getRecords();
        long current = staffPage.getCurrent();
        long total = staffPage.getTotal();
        long size = staffPage.getSize();
        return RL.listSuccess(records, null, total, current, size);
    }

    @PostMapping("/detail")
    public R<Staff> staffDetail(@RequestBody Staff staff) {
        LambdaQueryWrapper<Staff> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Staff::getId, staff.getId());
        Staff one = staffService.getOne(queryWrapper);
        return R.success(one, null);
    }

    //修改员工基本信息
    @PostMapping("/upStaff")
    public R<String> updateStaff(@RequestBody Staff staff) {
        LambdaQueryWrapper<Staff> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Staff::getPhone, staff.getPhone()).ne(Staff::getId, staff.getId());
        wrapper.and(w -> w.eq(Staff::getPhone, staff.getPhone()).ne(Staff::getId, staff.getId()));
        if (staffService.count(wrapper) > 0) {
            throw new CustomException(("手机号码已被注册使用"));
        }
        staffService.updateById(staff);
        return R.success(null, "修改成功");
    }

    //删除员工信息
    @PostMapping("/delStaff")
    public R<String> delStaff(@RequestBody Staff staff) {
        staffService.removeById(staff.getId());
        return R.success(null, "删除成功");
    }


    /**
     * 修改员工密码
     *
     * @param staff
     * @return
     */
    @PostMapping("/password")
    public R<String> changePassword(@RequestBody Staff staff) {
        LambdaQueryWrapper<Staff> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Staff::getPhone, staff.getPhone());
        Staff one = staffService.getOne(wrapper);

        String salt = UUID.randomUUID().toString().toUpperCase();
        String md5Password = Md5Utils.getMd5Password(staff.getPassword(), salt);
        one.setSalt(salt);
        one.setPassword(md5Password);

        if (StringUtils.isNotEmpty(one.getPassword())) {
            staffService.updateById(one);
        } else {
            staffService.save(one);
        }
        return R.success("", "修改密码成功");
    }

    /**
     * 登录后员工自行修改密码
     *
     * @param jsonObject
     * @return
     */
    @PostMapping("/loignChangePw")
    public R<String> loginChangePw(@RequestBody JSONObject jsonObject) {
        Long id = Long.valueOf(String.valueOf(jsonObject.get("id")));
        String originalPw = String.valueOf(jsonObject.get("originalPw"));
        String reConfirmPw = String.valueOf(jsonObject.get("reConfirmPw"));

        Staff staff = staffService.getById(id);
        String newMd5Password = Md5Utils.getMd5Password(originalPw, staff.getSalt());
        //判断原始密码是否一致

        if (!(staff.getPassword().equals(newMd5Password))) {
            throw new CustomException("原始密码错误");
        }
        //原始密码相等，修改密码成功
        String finnalMd5Password = Md5Utils.getMd5Password(reConfirmPw, staff.getSalt());
        staff.setPassword(finnalMd5Password);
        staffService.updateById(staff);
        return R.success("", "修改密码成功");
    }


    /**
     * 员工登录
     *
     * @param request
     * @param staff
     * @return
     */
    @PostMapping("/login")
    public R<Object> login(HttpServletRequest request, @RequestBody Staff staff) {
        String password = staff.getPassword();

        //2.根据页面提交的用户名电话号码查询数据库
        LambdaQueryWrapper<Staff> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Staff::getPhone, staff.getPhone());
        Staff one = staffService.getOne(queryWrapper);

        //3.没有查询到返回登录失败结果
        if (one == null) {
            return R.error("登录失败");
        } else {
            String md5Password = Md5Utils.getMd5Password(password, one.getSalt());
            if (one.getStatus() == 1) {
                return R.error("账号已禁用");
            }
            if (!md5Password.equals(one.getPassword())) {
                return R.error("账号或密码错误");
            }
        }
        String token = createJWT(one.getName());
        //6.登录成功，将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("staff", one);
        HashMap<String, Object> userInfo = new HashMap<>();

        userInfo.put("staff", one);
        userInfo.put("token", token);

        return R.success(userInfo, "登录成功");

    }

    /**
     * 员工绑定的权限
     *
     * @param phone
     * @return
     */
    @GetMapping("/rMList")
    public R<List> roleMenu(String phone) {
        LambdaQueryWrapper<Staff> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(Staff::getPhone, phone);
        Staff one = staffService.getOne(userLambdaQueryWrapper);
        long roleId = Long.parseLong(one.getPositionCode().substring(20));

        LambdaQueryWrapper<MenuRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MenuRole::getRoleId, roleId);
        List<MenuRole> list = menuRoleService.list(wrapper);


        List<Long> collect = list.stream().map((item) -> {
            return item.getMenuId();
        }).collect(Collectors.toList());

        LambdaQueryWrapper<www.ym.com.entity.menu.Menu> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(Menu::getId, collect);
        List<Menu> list1 = menuService.list(wrapper1);

        List<Long> parentIds = list1.stream().map(item -> {
            return item.getParentId();
        }).collect(Collectors.toList());

        LambdaQueryWrapper<Menu> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.in(Menu::getId, parentIds);
        List<Menu> list2 = menuService.list(wrapper2);

        for (Menu item : list2) {
            list1.add(item);
        }
        return R.success(list1, "");
    }
//
//    /**
//     * 员工退出
//     *
//     * @param request
//     * @return
//     */
//    @PostMapping("/logout")
//    public R<String> logout(HttpServletRequest request) {
//        //清理Session中保留的当前登录员工的id
//        request.removeAttribute("employee");
//        return R.success("退出成功");
//    }
//
//    /**
//     * 添加用户
//     * @param request
//     * @param employee
//     * @return
//     */
//    @PostMapping
//    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
//        //设置初始密码123456，需要进行md5加密处理
//        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
//
////        employee.setCreateTime(LocalDateTime.now());
////        employee.setUpdateTime(LocalDateTime.now());
////
////        //获取当前用户的id
////        Long empId = (Long) request.getSession().getAttribute("employee");
////        employee.setCreateUser(empId);
////        employee.setUpdateUser(empId);
//
//        employeeService.save(employee);
//        return R.success("新增员工成功");
//    }
//
//    /**
//     * 员工信息分页查询
//     * @param page
//     * @param pageSize
//     * @param name
//     * @return
//     */
//    @GetMapping("/page")
//    public R<Page> page(int page,int pageSize,String name){
//        log.info("page={}","pageSize={}","name={}",page,pageSize,name);
//        //构造分页构造器
//        Page pageinfo = new Page(page, pageSize);
//        //构造条件构造器
//        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();
//        //添加过滤条件
//        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
//        //添加排序条件
//        queryWrapper.orderByDesc(Employee::getUpdateTime);
//        //执行查询
//        employeeService.page(pageinfo,queryWrapper);
//        return R.success(pageinfo);
//    }
//
//    /**
//     * 根据id修改员工信息
//     * @param request
//     * @param employee
//     * @return
//     */
//    @PutMapping
//    public R<String> update(HttpServletRequest request,@RequestBody Employee employee){
////        Long empId = (Long)request.getSession().getAttribute("employee");
////        employee.setUpdateTime(LocalDateTime.now());
////        employee.setUpdateUser(empId);
//        employeeService.updateById(employee);
//        return R.success("员工信息修改成功");
//    }
//
//    /**
//     * 根据id查询员工信息
//     * @param
//     * @return
//     */
//    @GetMapping("/{id}")
//    public R<Employee> getById(@PathVariable Long id){
//        Employee employee = employeeService.getById(id);
//        if(employee!=null){
//            return R.success(employee);
//        }
//        return R.error("没有查询到对应员工消息");
//    }

}
